import {mongo} from "#nuxt-mongodb"
import {ObjectId} from "mongodb"

interface userUpdateNameInter {
    id:string,
    phone: string,
    new_name:string,
}

export default defineEventHandler(async(event:any)=>{
    const {id,phone,new_name}:userUpdateNameInter = await readBody(event)
    if(new_name == ''){
        return {
            status: 500,
            message: "新的名字为空,更改失败"
        }
    }else if(id == ''){
        return {
            status: 500,
            message: "用户id是空的,更改失败"
        }
    }else if(phone == ''){
        return {
            status: 500,
            message: "账号是空的,更改失败"
        }
    }
     // 将字符串 ID 转换为 ObjectId
    const objectId = new ObjectId(id);
    // console.log(objectId,phone,new_name)
    // 构建查询条件
    const query = { _id: objectId, account: phone };
    
    // 构建更新操作
    const update = { $set: { name: new_name } };
    console.log(query,update)
    const result = await mongo.db().collection('user').updateOne(query,update)
    if(result.matchedCount > 0){
        return {
            status: 200,
            data: result,
            message: `用户名更换成功,用户名为:${new_name}`
        }
    }else{
        return {
            status: 500,
            message: '用户名更换失败'
        }
    }
    
})